﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace TfsExtensions.Build.Activities.Entities
{
    public struct AssemblySigningSettings
    {
        public bool IsAssemblySigning { get; set; }
        public bool IsDelaySigned { get; set; }
        public string StrongKeyName { get; set; }
        public string StrongKeyFilePath { get; set; }
        public byte[] SignKeyContent { get; set; }
        //todo: add a bit array

        private StringBuilder objSignDetails;

        public override string ToString()
        {
            objSignDetails = new StringBuilder();
            objSignDetails.Append(string.Format("Signing: {0} ", this.IsAssemblySigning));
            objSignDetails.Append(Environment.NewLine);

            objSignDetails.Append(string.Format("Delay Signing: {0} ", this.IsDelaySigned));
            objSignDetails.Append(Environment.NewLine);

            if (this.IsAssemblySigning)
            {
                this.GetSigningDetails(objSignDetails);
            }

            return objSignDetails.ToString();
        }


        /// <summary>
        /// Gets the signing details.
        /// </summary>
        /// <param name="objSignDetails">The obj sign details.</param>
        private void GetSigningDetails(StringBuilder objSignDetails)
        {
            if (!string.IsNullOrEmpty(this.StrongKeyFilePath))
            {
                var keyfile = this.StrongKeyFilePath;
                keyfile = keyfile.Substring(keyfile.LastIndexOf(@"\") + 1);
                string filePath = Path.Combine(Path.GetTempPath(), keyfile);
                
                using (var mstream = new MemoryStream(SignKeyContent))
                {
                    using (var fstream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                    {
                        mstream.WriteTo(fstream);
                        fstream.Flush();
                        mstream.Flush();
                    }
                }

                objSignDetails.Append(string.Format("AssemblyKeyFile: {0} ", filePath));
                objSignDetails.Append(Environment.NewLine);
            }

            if (!string.IsNullOrEmpty(this.StrongKeyName))
            {
                objSignDetails.Append(string.Format("AssemblyKeyName: {0} ", this.StrongKeyName));
                objSignDetails.Append(Environment.NewLine);
            }
        }
    }
}
